<template>
    <div>
        <Header></Header>
        <el-row style="position: absolute; top: 60px; right: 0; left: 0; bottom: 0; ">
            <el-col :xs="24" :sm="{span: 12, offset: 6}" style="height: 100%;">
                <div class="grid-content bg-purple">
                    <div class="talk_title">聊天室</div>
                    <div class="talk_con2">
                        <!-- 显示区域 -->
                        <div class="talk_show">
                            <!-- 根据vue对象中的数组，遍历出对应的标签。 -->
                            <div v-for="i in arr" :class="i.id==userInfo.id ? 'btalk':'atalk'">
                                <div style="overflow: hidden">
                                    <el-avatar class="avatar" :src="'/api'+i.avatar"></el-avatar>
                                </div>
                                <div class="span">{{ i.username }}：{{ i.words }}</div>
                            </div>
                        </div>

                        <!-- 发送内容区域 -->
                        <div class="talk_input">
                            <!-- 请输入内容 -->
                            <input type="text" class="talk_word" v-model='msg'>
                            <!-- 按钮 -->
                            <input type="button" value="发送" class="talk_sub" @click="add_data()">
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>


    </div>
</template>

<script>
    import Header from "../components/Header";

    export default {
        name: "Chat",

        // 3.定义变量
        data() {
            return {
                path: "/ws/chat/",
                userInfo: {},
                socket: "",
                arr: [],
                msg: '',
            }
        },
        computed: {
            // ws处理请求
            idPath() {
                //根据http协议判断是否为ws或wss
                let proto = document.location.protocol == 'http:' ? 'ws:' : 'wss:';
                //取地址+端口，配置80端口时port是空的，所以判断一下
                let address = document.location.port ?
                    document.location.hostname + ':' + document.location.port : document.location.hostname;
//拼接请求地址
                const socketUrl = proto + "//" + address + this.path + this.userInfo.id;

                socketUrl.replace("https", "ws").replace("http", "ws");
                console.log(socketUrl);
                return socketUrl;
            }
        },
        components: {
            Header
        },
        // 4.定义方法
        methods: {
            add_data: function () {
                // bug: 内容不能为空。
                if (this.msg == '') {
                    alert('请输入内容...')
                    return;
                }
                var obj = {id: '1', words: this.msg, type: '1'}
                var form = {...this.userInfo, words: this.msg}
                // this.arr.push(obj)
                this.socket.send(JSON.stringify(form))
                // 添加完内容，清空
                this.msg = ''
            },
            init: function () {
                if (typeof (WebSocket) === "undefined") {
                    alert("您的浏览器不支持socket")
                } else {
                    // 实例化socket
                    this.socket = new WebSocket(this.idPath)
                    // 监听socket连接
                    this.socket.onopen = this.open
                    // 监听socket错误信息
                    this.socket.onerror = this.error
                    // 监听socket消息
                    this.socket.onmessage = this.getMessage
                }
            },
            open: function () {
                console.log("socket(聊天室)连接成功")
            },
            error: function () {
                console.log("连接错误")
            },
            getMessage: function (msg) {
                console.log(msg.data)
                this.arr.push(JSON.parse(msg.data))
            },
            close: function () {
                console.log("socket已经关闭")
            }
        },
        beforeMount() {
            this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        },
        mounted() {
            // 初始化
            this.init()
        },
        destroyed() {
            // 销毁监听
            this.socket.onclose();
            this.close();
        }
    }
</script>

<style scoped>

    .bg-purple {
        background: #d3dce6;
    }

    .grid-content {
        height: 100%;
        display: flex;
        flex-direction: column;
        /*align-items: flex-start;*/
        border-radius: 4px;
    }

    .talk_title {
        box-sizing: border-box;
        width: 100%;
        line-height: 40px;
        text-align: center;
        font-size: 18px;
        border: 1px solid #666;
        border-bottom: 0;
    }

    .talk_con2 {
        flex: 1;
        box-sizing: border-box;
        width: 100%;
        min-height: 500px;
        border: 1px solid #666;
        background: #B3C0D1;
    }

    .talk_show {
        width: 90%;
        height: 88%;
        border: 1px solid #666;
        background: #fff;
        margin: 10px auto 0;
        /*overflow: auto;*/
    }

    .talk_input {
        width: 90%;
        margin: 10px auto 0;
    }

    .whotalk {
        width: 80px;
        height: 30px;
        float: left;
        outline: none;
    }

    .talk_word {
        width: 65%;
        height: 26px;
        padding: 0px;
        float: left;
        outline: none;
        text-indent: 10px;
    }

    .talk_sub {
        width: 30%;
        height: 30px;
        float: right;
    }

    .atalk {
        margin: 10px;
    }

    .atalk .span {
        margin-top: 4px;
        display: inline-block;
        background: #0181cc;
        border-radius: 10px;
        color: #fff;
        padding: 5px 10px;
    }

    .btalk {
        margin: 10px;
        text-align: right;
    }

    .avatar {
        float: right;
    }

    .atalk .avatar {
        float: left;
    }

    .btalk .span {
        margin-top: 4px;
        display: inline-block;
        background: #ef0707;
        border-radius: 10px;
        color: #fff;
        padding: 5px 10px;
    }
</style>
